package com.example.myys.ui.page.yyPage

import android.widget.Toast
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.IntrinsicSize
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.defaultMinSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.wrapContentWidth
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ScrollableTabRow
import androidx.compose.material3.Tab
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavController
import coil3.compose.AsyncImage
import com.example.myys.R
import com.example.myys.common.TopItem
import com.example.myys.data.entity.DataBean
import com.example.myys.ui.Resource
import com.example.myys.ui.StateHandler
import com.example.myys.ui.base.DialogWithImage
import com.example.myys.ui.base.SearchBar
import com.example.myys.viewModel.yyModel.YyViewModel

//顶部导航栏数据定义
object PagesYy {
    const val SC = "Sc" //收藏
    const val Tj = "Tj" //推荐
}
//音乐展示
@OptIn(ExperimentalFoundationApi::class)
@Composable
fun Yy(navController: NavController, modifier: Modifier) {
    val yyViewModel: YyViewModel = viewModel()
    val scTjState by yyViewModel.scTjState.collectAsState()
    val sjState by yyViewModel.sjState.collectAsState()
    //导航
    val dataBar= listOf(
        TopItem(PagesYy.SC,"收藏"),
        TopItem(PagesYy.Tj,"推荐")
    )
    var state by remember { mutableStateOf(0) }
    val scope= rememberCoroutineScope()
    Column {
        ScrollableTabRow(selectedTabIndex = state) {
            dataBar.forEachIndexed { index, item ->
                Tab(text = {
                    Text(text = item.label)
                }, selected = state == index, onClick = {
                    state = index
                })
            }
        }
        when (state) {
                0-> YySc(sjState,navController,yyViewModel)
                1-> YyTj(scTjState,navController,yyViewModel)
            }

    }
    DisposableEffect(Unit) {
        onDispose {
            yyViewModel.stopMusic()
        }
    }
}

@Composable
fun YySc(sjState: Resource<List<DataBean>>, navController: NavController, marsViewModel: YyViewModel){
    StateHandler(state = sjState) { resource ->
        resource.data?.let { sjList ->
            Column {
                LazyColumn(modifier = Modifier.weight(1f)) {
                    items(
                        items = sjList
                    ) {
                        LocalMusicRVItem(musicBean = it, onClickItem = {marsViewModel.playMusicInMusicBean(it)})
                    }
                }
                BottomControlLayout(marsViewModel)
            }
        }
    }
}
@Composable
fun YyTj(scTjState: Resource<List<DataBean>>, navController: NavController, marsViewModel: YyViewModel){
    Column {
        SearchBar(onSearchClick = {
            marsViewModel.getSearchMusic(it)
        })
        StateHandler(state = scTjState) {resource ->resource.data?.let { scList->
            LazyColumn(modifier = Modifier.weight(1f)) {
                itemsIndexed(scList) { index, item ->
                    ItemYy(
                        item,
                        navController,
                        marsViewModel,
                        saveMusicSelf ={ marsViewModel.addMusicShelf(item) })
                }
            }
        }}
        BottomControlLayout(marsViewModel)
    }
}
@Composable
fun ItemYy(itemData: DataBean, navController: NavController, marsViewModel: YyViewModel, saveMusicSelf: () -> Unit) {
    // 获取 context
    val context = LocalContext.current
    //详情弹窗
    var dialogShow by remember {
        mutableStateOf(false)
    }
    LocalMusicRVItem(onClickItem = { dialogShow = true }, musicBean = itemData)
    if (dialogShow) {
        DialogWithImage(
            onDismissRequest = { dialogShow = false },
            onPlay = {
                marsViewModel.playMusicInMusicBean(itemData)
            },
            onConfirmation = {
                saveMusicSelf()
                Toast.makeText(context, "加入收藏成功", Toast.LENGTH_SHORT).show()
                dialogShow = false
            },
            itemData
        )
    }
}
@Composable
fun LocalMusicRVItem(musicBean: DataBean,onClickItem:()->Unit) {

    Column(modifier = Modifier
        .clickable {
            onClickItem()
        }
        .height(IntrinsicSize.Min)) {

        Text(
            musicBean.name,
            modifier = Modifier
                .padding(5.dp),
            style = MaterialTheme.typography.titleMedium,
            maxLines = 1
        )

        Row{
            Text(
                musicBean.author,
                modifier = Modifier
                    .padding(5.dp)
                    .wrapContentWidth(Alignment.Start)
                    .weight(1f),

            )

            Text(
                musicBean.updateTime,
                modifier = Modifier
                    .padding(5.dp)
                    .wrapContentWidth(Alignment.End)
                    .weight(1f),
            )
        }
    }
}
@Composable
fun BottomControlLayout(mViewModel: YyViewModel) {

    val localMusicBean: DataBean by mViewModel.localMusicBean.observeAsState(
        DataBean()
    )

    Row(
        modifier = Modifier
            .fillMaxWidth()
            .height(IntrinsicSize.Min)
            .defaultMinSize(0.dp, 80.dp)
            .background(MaterialTheme.colorScheme.primary),
        verticalAlignment = Alignment.CenterVertically
    ) {

        // 歌曲图标
        Box(Modifier.weight(1f), contentAlignment = Alignment.Center) {
            AsyncImage(
                modifier = Modifier
                    .clip(CircleShape)
                    .size(60.dp)
                    .wrapContentWidth(Alignment.CenterHorizontally),
                model = localMusicBean.cover,
                contentDescription = localMusicBean.name,
                contentScale = ContentScale.Crop
            )
        }

        // 歌曲信息
        Column(
            Modifier
                .fillMaxWidth()
                .weight(2f)) {
            Text(localMusicBean.name, style = MaterialTheme.typography.titleLarge)
            Text(localMusicBean.author, style = MaterialTheme.typography.titleLarge)
        }

        Row(
            Modifier
                .fillMaxWidth()
                .wrapContentWidth(Alignment.CenterHorizontally)
                .weight(2f),
            verticalAlignment = Alignment.CenterVertically, //设置垂直方向对齐
            horizontalArrangement = Arrangement.spacedBy(10.dp) //设置子项的间距
        ) {

            val isPlaying by mViewModel.isPlaying.observeAsState(false)

            // 上一首按钮
            Image(painter = painterResource(id = R.drawable.ic_last),
                contentDescription = "上一首",
                modifier = Modifier
                    .clickable { mViewModel.playLastMusic() }
                    .size(30.dp)
            )

            // 播放暂停按钮
            Image(painter = if (isPlaying) {
                painterResource(id = R.drawable.ic_pause)
            } else {
                painterResource(id = R.drawable.ic_play)
            },
                contentDescription = "播放或者暂停",
                modifier = Modifier
                    .clickable { mViewModel.playCurrentMusic() }
                    .size(40.dp)
            )

            // 下一首按钮
            Image(painter = painterResource(id = R.drawable.ic_next),
                contentDescription = "下一首",
                modifier = Modifier
                    .clickable { mViewModel.playNextMusic() }
                    .size(30.dp)
            )
        }
    }
}